<script setup lang="ts">
import Taro from "@tarojs/taro";
import { computed, inject, onMounted, reactive, Ref, ref } from "vue";

const props = withDefaults(
  defineProps<{
    mode?: "date";

    range?: any[];
    rangeKey?: string;

    valueKey?: string;
    placeholder?: string;

    disabled?: boolean;
  }>(),
  {
    disabled: undefined,
  }
);

const formProps = inject<{
  disabled: Ref<boolean>;
}>("ByForm");

const modelValue = defineModel<any>();

const item = computed(() => {
  const { mode, range, valueKey } = props;
  const { value } = modelValue;

  if (mode != "date")
    return range?.find((e) => (valueKey ? e[valueKey] == value : e == value));

  return value;
});

const index = ref(0);
const handleChange = (e) => {
  const { mode, range, valueKey } = props;

  index.value = e.detail.value;
  const item = mode == "date" ? index.value : range?.[index.value];
  modelValue.value = valueKey && mode != "date" ? item[valueKey] : item;
};

const elId = `id_${new Date().getDate()}`;
const react = reactive<{ width?: string; height?: string }>({});
onMounted(() => {
  setTimeout(() => {
    Taro.createSelectorQuery()
      .select(`#${elId}`)
      .boundingClientRect()
      .exec((e) => {
        react.width = e[0]["width"] + "px";
        react.height = e[0]["height"] + "px";
      });
  }, 300);
});

const disabled = computed(() => {
  const flag = props.disabled ?? formProps?.disabled;
  // 内置组件 h5模式下，应用反了
  return process.env.TARO_ENV === "h5" ? !flag : flag;
});
</script>

<template>
  <picker
    :id="elId"
    :mode="mode"
    :range="range"
    :rangeKey="rangeKey"
    :disabled="disabled"
    class="flex-auto h-full flex items-center"
    @change="handleChange"
  >
    <view class="flex items-center" :style="react">
      <text v-if="item">{{ item && rangeKey ? item[rangeKey] : item }}</text>
      <text v-else class="text-second">{{ placeholder }}</text>
    </view>
  </picker>
</template>
